<template>
  <div class="bg-white _p-20 tabsNoneMargin">
    <div class="fz-16 title linh-48 _mb-20">
      <span>活动详情介绍</span>
      <span class="_pl-20 color9 fz-14" style="color: #969799;"
        >（可以自由增加多个介绍活动的模块，例如增加活动进程、活动嘉宾介绍等）</span
      >
    </div>
    <div class="disFlxAC">
      <a-tabs :activeKey="currentId" type="editable-card" :hideAdd="true" @change="handleChange" @edit="handleTabsEdit">
        <a-tab-pane
          v-for="(item, index) in activeDetailsList"
          :key="item.id"
          :tab="item.moduleName"
          :closable="index !== 0 && !disableEditing"
        ></a-tab-pane>
      </a-tabs>
      <a-button
        v-if="activeDetailsList.length < 3 && !disableEditing"
        class="_ml-15"
        type="primary"
        :loading="addLoading"
        @click="handleTabsEdit"
        >添加模块</a-button
      >
    </div>

    <div style="border:solid 1px #e8e8e8">
      <a-form-model
        class="_pt-10"
        ref="form"
        :rules="rules"
        :model="currentItem"
        labelAlign="right"
        layout="horizontal"
        :labelCol="{
          xs: { span: 24 },
          sm: { span: 3 }
        }"
        :wrapperCol="{
          xs: { span: 24 },
          sm: { span: 12 }
        }"
      >
        <a-form-model-item label="模块名称" prop="moduleName">
          <a-input
            v-model="currentItem.moduleName"
            :disabled="currentId === activeDetailsList[0].id || disableEditing"
            placeholder="请输入模块名称"
            :maxLength="8"
          />
        </a-form-model-item>
        <a-form-model-item label="活动详情" prop="introduce" :disabled="disableEditing">
          <Ueditor
            v-if="currentItem.id && editorReady"
            :key="currentItem.id"
            v-model="currentItem.introduce"
            :editorId="String(currentItem.id)"
            :disabled="disableEditing"
          />
        </a-form-model-item>
      </a-form-model>
    </div>
    <slot></slot>
  </div>
</template>

<script>
import Ueditor from '@/components/Ueditor'
import { isNumber, cloneDeep, isString } from 'lodash-es'
import { getUnionActivityDetailList } from '@/api/activity/activity'
import { ActivitySettlementStatusEnum } from '@/enums/activity'

export default {
  components: {
    Ueditor
  },
  props: {
    info: {
      type: Object,
      default: () => ({})
    }
  },
  mounted() {
    this.init()
  },
  data() {
    return {
      routeName: 'activityCreate',
      activityId: undefined,
      activeDetailsList: [{ moduleName: '活动详情', introduce: '', id: new Date().getTime() }], // 活动详情列表
      form: {
        id: undefined,
        moduleName: undefined,
        introduce: undefined
      },
      addLoading: false,
      currentId: undefined,
      currentItem: {},
      rules: {
        moduleName: [{ required: true, message: '请输入模块名称', trigger: ['blur', 'change'] }]
      },
      editorReady: false
    }
  },
  computed: {
    disabled() {
      return this.info.activityType === 'other_join' // 协办方
    },
    disableEditing() {
      return (
        [
          ActivitySettlementStatusEnum.PROGRESS,
          ActivitySettlementStatusEnum.SUCCESS,
          ActivitySettlementStatusEnum.PART_SUCCESS
        ].includes(this.info.settleStatus) || this.disabled
      )
    }
  },
  methods: {
    init() {
      this.routeName = this.$route.name
      const { activityId } = this.$route.query
      if (activityId) {
        this.activityId = activityId
        this.getDetailsGroup() // 获取活动详情
      } else {
        this.handleChange(this.activeDetailsList[0].id)
      }
    },
    // 获取详情列表
    async getDetailsGroup() {
      const { data } = await getUnionActivityDetailList(this.activityId)
      this.activeDetailsList = cloneDeep(data)
      if (!this.form.id && data.length) {
        this.handleChange(data[0].id)
      }
    },
    handleChange(id) {
      const detailsListItem = this.activeDetailsList.find(item => item.id == id)
      this.currentId = id
      if (detailsListItem) {
        this.currentItem = detailsListItem
      }
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.validate()
      })
      this.$nextTick(() => {
        const targetElement = document.querySelector('.has-error')
        if (targetElement) {
          targetElement.scrollIntoView({ behavior: 'smooth' })
        }
        this.editorReady = true;

      }, 100)
    },
    async handleTabsEdit(targetKey) {
      if (isNumber(targetKey) || isString(targetKey)) {
        // 删除
        this.$confirm({
          title: `删除${this.currentItem.moduleName}模块`,
          content: `确定要删除活动介绍模块“${this.currentItem.moduleName}”吗？删除后将会把模块及内容一并删除。`,
          okText: '确定删除',
          okType: 'danger',
          cancelText: '取消',
          onOk: () => {
            const currentIndex = this.activeDetailsList.findIndex(item => item.id === targetKey)
            this.activeDetailsList = this.activeDetailsList.filter(item => item.id !== targetKey)
            this.handleChange(this.activeDetailsList[currentIndex - 1].id)
          }
        })
      } else {
        const id = new Date().getTime()
        this.activeDetailsList.push({
          id,
          introduce: '',
          moduleName: `介绍模块${this.activeDetailsList.length + 1}`
        })
        this.handleChange(id)
      }
    },
    saveForm() {
      return new Promise((resolve, reject) => {
        const activeDetailsListItem = this.activeDetailsList.find(item => !item.moduleName)
        if (!activeDetailsListItem) {
          resolve(this.activeDetailsList)
        } else {
          this.handleChange(activeDetailsListItem.id)
          reject('活动详情介绍表单校验未通过')
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.title {
  color: #1d2129;
  border-bottom: solid 1px #e5e6eb;
}

.tabsNoneMargin /deep/ .ant-tabs-bar {
  margin: 0;
  border-bottom: none;
}

.tabsNoneMargin /deep/ .edui-editor {
  z-index: 8 !important;
}
</style>
